import Vue from 'vue'
import router from './router'
import store from './store'
import {
	Message
} from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
NProgress.configure({
	easing: 'ease', // 动画方式
	speed: 500, // 递增进度条的速度
	showSpinner: false, // 是否显示加载ico
	trickleSpeed: 200, // 自动递增间隔
	minimum: 0.3, // 初始化时的最小百分比
})

const whiteList = ['/Login','/Register'] //当前路由不需要验证token

router.beforeEach(async (to, from, next) => {
	// localStorage.clear()
	// start progress bar
	NProgress.start()
	//获取用户token
	const hasToken = Vue.prototype.$lzStore.get('token')
	if (hasToken) {
		if (to.path === '/Login') {
			// if is logged in, redirect to the home page
			next({
				path: '/'
			})
			NProgress.done()
		} else {
			next()
			const hasGetUserInfo = Vue.prototype.$lzStore.get('userInfo') //当前用户
			if (hasGetUserInfo) {
				next()
			} else {
				// 获取用户信息失败
				await store.dispatch('user/resetToken')
				Message.error('获取用户信息失败')
				next(`/Login`)
			}
		}
	} else {
		//当前用户没有token
		console.log(to.path);
		if (whiteList.indexOf(to.path) !== -1) {
			// in the free login whitelist, go directly
			next()
		} else {
			// other pages that do not have permission to access are redirected to the login page.
			next(`/Login`)
			NProgress.done()
		}
	}
})

router.afterEach(() => {
	// finish progress bar
	NProgress.done()
})
